import React from "react";
import {inject, observer} from "mobx-react";
import {Tools, Modal, Button, List, InputItem} from "weaver-mobile";
import {getDynamicPassword} from "../../apis/secondAuth";
import * as authTypes from "../../constants/secondAuthType";

const getLabel = Tools.getLabel;
const Item = List.Item;

@observer
export default class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {countDown: -1, showButton: false};
    }

    componentDidMount() {
        const {needSend} = this.props;

        if (needSend) {
            this.getDynaPwd();
        }
    }

    componentDidUpdate() {
        let $this = this;
        let {countDown} = this.state;

        if (!this.intervalid && countDown > 0) {
            this.intervalid = window.setInterval(() => {
                countDown = countDown - 1;
                $this.setState({countDown});
            }, 1000);
        }

        if (!!this.intervalid && countDown <= 0) {
            window.clearInterval(this.intervalid);
            this.intervalid = null;
        }
    }

    componentWillUnmount() {
        if (!!this.intervalid) {
            window.clearInterval(this.intervalid);
        }
    }

    saveAuthCode(val) {
        const {secondAuthStore} = this.props;
        secondAuthStore.saveAuthCode(val);
    }

    /**
     * 获取动态密码
     */
    getDynaPwd() {
        getDynamicPassword({}).then(data => {
            let {api_status, api_errormsg, validSecond} = data;

            if (!api_status) {      //发送二次授权码失败
                this.setState({showButton: true});
                if (!!api_errormsg) {
                    Modal.error({content: api_errormsg});
                }
            } else {    //发送成功
                this.setState({showButton: false, countDown: validSecond});
            }
        });
    }

    render() {
        const {countDown, showButton} = this.state;
        return (
            <List>
                <InputItem
                    placeholder={getLabel(501199, "请输入动态密码")}
                    extra={
                        countDown > 0 && <span className="dynamicPwdAppend">{`${countDown}s`}</span>
                    }
                    onChange={this.saveAuthCode.bind(this)}
                    className="ca-auth-inputitem"
                />

                {
                    (countDown == 0 || showButton) &&
                    <Item className="message-btn">
                        <Button type="ghost"
                                size="small"
                                inline={true}
                                onClick={this.getDynaPwd.bind(this)}>{getLabel(22408, "重新发送")}</Button>
                    </Item>
                }
            </List>
        );
    }
}
